// 管理员端热门推荐管理云函数
const db = uniCloud.database();
const _ = db.command;

// 管理员权限验证
async function checkAdminPermission(context) {
  const openid = context?.OPENID || '';
  
  // 查询管理员集合
  const adminRes = await db.collection('admin')
    .where({ openid: openid })
    .get();
  
//   if (adminRes.data.length === 0) {
//     throw new Error('无管理员权限');
//   }
  
//   return true;
}

// 获取热门推荐列表
async function getFeaturedList(context) {
  // await checkAdminPermission(context);
  
  // 先检查是否有featured集合
  const collections = await db.collection('collection').get();
  let hasFeaturedCollection = collections.data.some(col => col.name === 'featured');
  
  // 如果没有featured集合，先创建一个
  if (!hasFeaturedCollection) {
    // await db.createCollection('featured');
  }
  
  // 查询热门推荐列表（按排序字段升序）
  const res = await db.collection('featured')
    .orderBy('sort', 'asc')
    .get();
  
  // 如果没有数据，返回空数组
  if (res.data.length === 0) {
    return {
      code: 200,
      data: [],
      message: '暂无热门推荐数据'
    };
  }
  
  // 获取壁纸详情
  const wallpaperIds = res.data.map(item => item.wallpaper_id);
  const wallpapersRes = await db.collection('wallpapers')
    .where({
      _id: _.in(wallpaperIds)
    })
    .get();
  
  // 创建壁纸ID到壁纸信息的映射
  const wallpaperMap = wallpapersRes.data.reduce((map, wallpaper) => {
    map[wallpaper._id] = wallpaper;
    return map;
  }, {});
  
  // 合并热门推荐和壁纸信息，并过滤掉不存在的壁纸
  const featuredList = res.data
    .map(item => {
      const wallpaper = wallpaperMap[item.wallpaper_id];
      return {
        ...item,
        wallpaper: wallpaper
      };
    })
    .filter(item => item.wallpaper !== undefined); // 只保留有壁纸信息的记录
  
  return {
    code: 200,
    data: featuredList,
    message: '获取热门推荐列表成功'
  };
}

// 添加热门推荐
async function addFeatured(event, context) {
  // await checkAdminPermission(context);
  
  const { wallpaper_id, sort } = event;
  
  // 参数校验
  if (!wallpaper_id) {
    throw new Error('壁纸ID不能为空');
  }
  
  // 检查壁纸是否存在
  const wallpaperRes = await db.collection('wallpapers').doc(wallpaper_id).get();
  if (!wallpaperRes.data) {
    throw new Error('壁纸不存在');
  }
  
  // 检查是否已在热门推荐中
  const existingRes = await db.collection('featured')
    .where({ wallpaper_id })
    .get();
  
  if (existingRes.data.length > 0) {
    throw new Error('该壁纸已在热门推荐中');
  }
  
  // 获取当前最大排序值
  const maxSortRes = await db.collection('featured')
    .orderBy('sort', 'desc')
    .limit(1)
    .get();
  
  const newSort = sort !== undefined ? Number(sort) : 
    (maxSortRes.data.length > 0 ? maxSortRes.data[0].sort + 1 : 1);
  
  // 添加到热门推荐
  const now = new Date();
  const res = await db.collection('featured').add({
    data: {
      wallpaper_id,
      sort: newSort,
      create_time: now,
      update_time: now
    }
  });
  
  return {
    code: 200,
    data: { _id: res._id },
    message: '添加热门推荐成功'
  };
}

// 更新排序
async function updateFeaturedSort(event, context) {
  // await checkAdminPermission(context);
  
  const { _id, sort } = event;
  
  // 参数校验
  if (!_id || sort === undefined) {
    throw new Error('热门推荐ID和排序值不能为空');
  }
  
  // 更新排序
  await db.collection('featured').doc(_id).update({
    data: {
      sort: Number(sort),
      update_time:new Date()
    }
  });
  
  return {
    code: 200,
    message: '更新排序成功'
  };
}

// 移除热门推荐
async function removeFeatured(event, context) {
  // await checkAdminPermission(context);
  
  const { _id } = event;
  
  // 参数校验
  if (!_id) {
    throw new Error('热门推荐ID不能为空');
  }
  
  // 移除热门推荐
  await db.collection('featured').doc(_id).remove();
  
  return {
    code: 200,
    message: '移除热门推荐成功'
  };
}

// 批量添加热门推荐
async function batchAddFeatured(event, context) {
  // await checkAdminPermission(context);
  
  const { wallpaper_ids } = event;
  
  // 参数校验
  if (!Array.isArray(wallpaper_ids) || wallpaper_ids.length === 0) {
    throw new Error('壁纸ID数组不能为空');
  }
  
  // 检查壁纸是否都存在
  const wallpapersRes = await db.collection('wallpapers')
    .where({
      _id: _.in(wallpaper_ids)
    })
    .get();
  
  // 获取存在的壁纸ID集合
  const existingWallpaperIds = new Set(wallpapersRes.data.map(wp => wp._id));
  
  // 找出不存在的壁纸ID
  const nonExistentIds = wallpaper_ids.filter(id => !existingWallpaperIds.has(id));
  
  // 筛选出存在的壁纸ID
  const validWallpaperIds = wallpaper_ids.filter(id => existingWallpaperIds.has(id));
  
  if (validWallpaperIds.length === 0) {
    throw new Error('所有壁纸ID都不存在');
  }
  
  // 检查是否已在热门推荐中
  const existingRes = await db.collection('featured')
    .where({
      wallpaper_id: _.in(validWallpaperIds)
    })
    .get();
  
  const existingIds = existingRes.data.map(item => item.wallpaper_id);
  const newWallpaperIds = validWallpaperIds.filter(id => !existingIds.includes(id));
  
  if (newWallpaperIds.length === 0) {
    throw new Error('所有存在的壁纸都已在热门推荐中');
  }
  
  // 获取当前最大排序值
  const maxSortRes = await db.collection('featured')
    .orderBy('sort', 'desc')
    .limit(1)
    .get();
  
  let currentSort = maxSortRes.data.length > 0 ? maxSortRes.data[0].sort + 1 : 1;
  
  // 批量添加
  const now = new Date();
  const batch = db.batch();
  
  newWallpaperIds.forEach(id => {
    batch.add(db.collection('featured'), {
      data: {
        wallpaper_id: id,
        sort: currentSort++,
        create_time: now,
        update_time: now
      }
    });
  });
  
  await batch.commit();
  
  // 构建返回消息，包含不存在的壁纸ID信息
  let message = `成功添加 ${newWallpaperIds.length} 个热门推荐`;
  if (nonExistentIds.length > 0) {
    message += `，其中 ${nonExistentIds.length} 个壁纸ID不存在：${nonExistentIds.join(',')}`;
  }
  
  return {
    code: 200,
    message: message,
    data: {
      addedCount: newWallpaperIds.length,
      nonExistentIds: nonExistentIds
    }
  };
}

// 主入口函数
exports.main = async (event, context) => {
  try {
    const { action } = event;
    
    switch (action) {
        case 'getList':
          return await getFeaturedList(context);
        case 'add':
          return await addFeatured(event, context);
        case 'updateSort':
          return await updateFeaturedSort(event, context);
        case 'remove':
          return await removeFeatured(event, context);
        case 'batchAdd':
          return await batchAddFeatured(event, context);
        default:
          throw new Error('无效的操作类型');
      }
  } catch (error) {
    return {
      code: 400,
      message: error.message || '操作失败'
    };
  }
};